const { prisma } = require('../config/prisma');

class PackagePrisma {
  constructor(data) {
    this.id = data.id;
    this.title = data.title;
    this.description = data.description;
    this.price = data.price;
    this.credits_amount = data.credits_amount;
    this.package_type = data.package_type;
    this.is_active = data.is_active;
    this.sort_order = data.sort_order;
    this.created_at = data.created_at;
    this.updated_at = data.updated_at;
  }

  /**
   * 根据ID查找套餐
   * @param {number} id 套餐ID
   * @returns {Promise<PackagePrisma|null>}
   */
  static async findById(id) {
    const packageData = await prisma.packages.findUnique({
      where: { id: parseInt(id) }
    });
    return packageData ? new PackagePrisma(packageData) : null;
  }

  /**
   * 获取套餐列表（支持分页和筛选）
   * @param {Object} options 查询选项
   * @returns {Promise<{data: PackagePrisma[], pagination: Object}>}
   */
  static async getList(options = {}) {
    const {
      page = 1,
      pageSize = 10,
      is_active,
      search,
      package_type,
      orderBy = { created_at: 'desc' }
    } = options;

    const skip = (page - 1) * pageSize;
    const take = parseInt(pageSize);

    // 构建查询条件
    const where = {};

    if (is_active !== undefined) {
      where.is_active = is_active;
    }

    if (package_type) {
      where.package_type = package_type;
    }

    if (search) {
      where.OR = [
        { title: { contains: search } },
        { description: { contains: search } }
      ];
    }

    // 获取总数
    const total = await prisma.packages.count({ where });

    // 获取数据
    const packages = await prisma.packages.findMany({
      where,
      orderBy,
      skip,
      take
    });

    const totalPages = Math.ceil(total / pageSize);

    return {
      data: packages.map(pkg => new PackagePrisma(pkg)),
      pagination: {
        page: parseInt(page),
        pageSize: take,
        total,
        totalPages
      }
    };
  }

  /**
   * 获取所有上架的套餐列表
   * @param {Object} options 查询选项
   * @returns {Promise<PackagePrisma[]>}
   */
  static async findActivePackages(options = {}) {
    const { orderBy = { sort_order: 'asc' } } = options;

    const packages = await prisma.packages.findMany({
      where: { is_active: true },
      orderBy
    });

    return packages.map(pkg => new PackagePrisma(pkg));
  }

  /**
   * 根据套餐类型获取上架的套餐列表
   * @param {string} packageType 套餐类型
   * @param {Object} options 查询选项
   * @returns {Promise<PackagePrisma[]>}
   */
  static async findActivePackagesByType(packageType, options = {}) {
    const { orderBy = { sort_order: 'asc' } } = options;

    const packages = await prisma.packages.findMany({
      where: {
        is_active: true,
        package_type: packageType
      },
      orderBy
    });

    return packages.map(pkg => new PackagePrisma(pkg));
  }

  /**
   * 获取所有套餐列表（管理后台用）
   * @param {Object} options 查询选项
   * @returns {Promise<{packages: PackagePrisma[], total: number}>}
   */
  static async findAll(options = {}) {
    const { 
      page = 1, 
      limit = 10, 
      orderBy = { created_at: 'desc' },
      where = {}
    } = options;
    
    const skip = (page - 1) * limit;
    
    const [packages, total] = await Promise.all([
      prisma.packages.findMany({
        where,
        orderBy,
        skip,
        take: limit
      }),
      prisma.packages.count({ where })
    ]);
    
    return {
      packages: packages.map(pkg => new PackagePrisma(pkg)),
      total
    };
  }

  /**
   * 创建新套餐
   * @param {Object} packageData 套餐数据
   * @returns {Promise<PackagePrisma>}
   */
  static async create(packageData) {
    const packageRecord = await prisma.packages.create({
      data: {
        title: packageData.title,
        description: packageData.description || null,
        price: packageData.price || 0,
        credits_amount: packageData.credits_amount,
        package_type: packageData.package_type,
        is_active: packageData.is_active !== undefined ? packageData.is_active : true,
        sort_order: packageData.sort_order || 0
      }
    });
    
    return new PackagePrisma(packageRecord);
  }

  /**
   * 更新套餐信息
   * @param {number} id 套餐ID
   * @param {Object} updateData 更新数据
   * @returns {Promise<PackagePrisma|null>}
   */
  static async update(id, updateData) {
    try {
      const packageRecord = await prisma.packages.update({
        where: { id: parseInt(id) },
        data: updateData
      });
      
      return new PackagePrisma(packageRecord);
    } catch (error) {
      if (error.code === 'P2025') {
        return null; // 记录不存在
      }
      throw error;
    }
  }

  /**
   * 删除套餐
   * @param {number} id 套餐ID
   * @returns {Promise<boolean>}
   */
  static async delete(id) {
    try {
      await prisma.packages.delete({
        where: { id: parseInt(id) }
      });
      return true;
    } catch (error) {
      if (error.code === 'P2025') {
        return false; // 记录不存在
      }
      throw error;
    }
  }

  /**
   * 上架/下架套餐
   * @param {number} id 套餐ID
   * @param {boolean} isActive 是否上架
   * @returns {Promise<PackagePrisma|null>}
   */
  static async updateActiveStatus(id, isActive) {
    return this.update(id, { is_active: isActive });
  }

  /**
   * 转换为JSON对象
   * @returns {Object}
   */
  toJSON() {
    return {
      id: this.id,
      title: this.title,
      description: this.description,
      price: parseFloat(this.price),
      credits_amount: this.credits_amount,
      package_type: this.package_type,
      is_active: this.is_active,
      sort_order: this.sort_order,
      created_at: this.created_at,
      updated_at: this.updated_at
    };
  }
}

module.exports = PackagePrisma;
